<?php

namespace app\db\admin;

use ltcms\db\Db_raw;

class D_singlePage
{
    /**
     * 信息格式化
     */
    protected function detailed($Result, $format)
    {
        // 更新时间
        if (isset($Result['updateTime'])) {
            $Result['updateTimeFormat'] = app("ltcmsTime")::getDateTime('Y-m-d H:i:s', $Result['updateTime']);
        }
        if (isset($Result['linkUrl'])) {  //存放文件名和路径
            $lastSlashIndex = strrpos($Result['linkUrl'], "/");
            if ($lastSlashIndex === false) {
                $Result['path'] = "/"; //根目录
            } else {
                $Result['path'] = substr($Result['linkUrl'], 0, $lastSlashIndex + 1);
            }
            $Result['path'] = ltrim($Result['path'], '/'); //删掉左侧斜杠
            //$Result['path'] =  dirname($Result['linkUrl']);  //有坑, /aaa.html 会返回 \
            $Result['file'] = basename($Result['linkUrl']);

        }
        if (isset($Result['isLink'])) {
            if ($Result['isLink']) {
                $Result["linkUrlFormat"] = $Result['linkUrl'];
            } else {
                //判断显示域名,用户是否填写了,域名, 如果没填写,使用系统域名
                $Result["linkUrlFormat"] = ($Result['domain']==""?config("app.url"):$Result['domain'] ) . $Result['linkUrl'];
                //判断是否有变量,如果有直接替换,列表页和标签会用到
                if (strpos( $Result["linkUrlFormat"],"{id}")!==false){
                    $Result["linkUrlFormat"]=str_replace("{id}",$Result["id"],$Result["linkUrlFormat"]);
                }
            }
        }

        if (isset($Result['style'])) {
            $Result['color'] = str_getBetween($Result['style'] . ";", "color:", ";");
        }
        // 返回结果
        return $Result;
    }

    /**
     * 获取数据详情
     * @param string $paramObj
     */
    public function info($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'id' => 'require|integer|gt:0',
                'field' => '',
                'format' => '',
                'verify' => '',
            );
            $dataDefault["verify"] = 1;
            $dataDefault["format"] = 1;
            $dataDefault["field"] = "*";
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $condition = array();
            $condition[] = array(
                "id", "=", $dataObj->request->id
            );
            try {
                $result = Db()->name(app("cmsTable")::single_page())->where($condition)->find();
                if ($dataObj->request->format) {
                    $result = $this->detailed($result, $dataObj->request->format);
                }
                if ($dataObj->request->verify) {
                    if (empty($result)) {
                        $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::DATA_NOT_EXIST, lang("sys.dataNotExists"));
                    }
                }


                if ($final_arr["error_no"] == 0 && $result) {
                    $final_arr["result"] = $result;
                }

            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**
     * 创建数据
     * @param string $paramObj
     */
    public function store($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                "item" => "",
                "level" => "must|between:0,127",
                "title" => "must|max:100",
                "style" => "",
                "seoTitle" => "",
                "seoKeywords" => "",
                "seoDescription" => "",
                "sort" => "",
                "isLink" => "number",
                "linkUrl" => "",
                "domain" => "",
                "template" => "",
                "content" => "",
            );

            $dataDefault = array(
                "item" => "1",
                "level" => "1",
                "sort" => "1",
                "isLink" => "0",
                "content" => "",               //text 字段不能设置默认值,而且添加时必须有值  但是外部链接是没有这个值,所有默认空字符串
            );

            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }


        //数据库操作============
        if ($final_arr["error_no"] == 0) {
            try {
                $data = array();
                $allowUpdates = ["item", "level", "title", "style", "seoTitle", "seoKeywords", "seoDescription", "sort", "isLink", "linkUrl", "domain", "template", "content"]; //允许更新的字段
                foreach ($dataObj->request as $key => $value) {
                    if (in_array($key, $allowUpdates) && $value !== null) {
                        $data[$key] = $value;
                    }
                }
                if(isset($data["content"])){
                    $data["content"]=dhtmlspecialchars($data["content"]);
                }
                $data["updateTime"] = time();
                $data["hits"] = 0;
                $result = Db()->name(app("cmsTable")::single_page())->prepare(false)->insert($data);
                $return = array();
                $return["id"] = $result["insert_id"];
                $return["affected_rows"] = $result["affected_rows"];
                $final_arr["result"] = $return;
            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**
     * 更新数据
     * @param string $paramObj
     */
    public function update($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'id' => 'require|integer|gt:0',
                "item" => "",
                "level" => "between:0,127",
                "title" => "max:100",
                "style" => "",
                "seoTitle" => "",
                "seoKeywords" => "",
                "seoDescription" => "",
                "sort" => "",
                "isLink" => "",
                "linkUrl" => "",
                "domain" => "",
                "template" => "",
                "content" => "",
                "verify" => "",
            );

            $dataDefault = array();
            $dataDefault["verify"] = 1;
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            if ($dataObj->request->verify) {
                $paramsObj = paramsObj();
                $paramsObj->params = array(
                    "id" => $dataObj->request->id,
                    "verify" => 1,
                );
                $checkResult = $this->info($paramsObj);
                if ($checkResult["error_no"] == 0) {

                } else {
                    $final_arr = logCallErrorMsg($final_arr, $checkResult);
                }
            }
        }

        if ($final_arr["error_no"] == 0) {
            $condition = array();
            $condition[] = array(
                "id", "=", $dataObj->request->id
            );

            $data = array();
            $allowUpdates = ["item", "level", "title", "style", "seoTitle", "seoKeywords", "seoDescription", "sort", "isLink", "linkUrl", "domain", "template", "content"]; //允许更新的字段
            foreach ($dataObj->request as $key => $value) {
                if (in_array($key, $allowUpdates) && $value !== null) {
                    $data[$key] = $value;
                }
            }
            if(isset($data["content"])){
                $data["content"]=dhtmlspecialchars($data["content"]);
            }
            if ($data) {
                try {
                    $result = Db()->name(app("cmsTable")::single_page())->where($condition)->data($data)->update();
                    $return = array();
                    $return["id"] = $dataObj->request->id;
                    $return["affected_rows"] = $result["affected_rows"];
                    $final_arr["result"] = $return;
                } catch (\Throwable $e) {
                    $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
                }
            } else {
                $return = array();
                $return["id"] = $dataObj->request->id;
                $return["affected_rows"] = 0;
                $final_arr["result"] = $return;
            }
        }
        return $final_arr;
    }

    /**
     * 删除数据
     * @param string $paramObj
     */
    public function delete($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'id' => 'require',
            );
            $dataDefault = array();
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            //判断 id是否为数组,如果是数组,返回id数组,如果不是数组,返回单成员数组
            $ids = is_array($dataObj->request->id) ? $dataObj->request->id : explode(",", $dataObj->request->id);
            $condition = array();
            $condition[] = array(
                "id", "in", $ids
            );
            try {
                $result = Db()->name(app("cmsTable")::single_page())->where($condition)->delete();
                $return = array();
                $return["affected_rows"] = $result["affected_rows"];
                $final_arr["result"] = $return;
            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**
     * 列表数据
     * @param string $paramObj
     */
    public function listData($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = array();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'order' => '',
                'type' => 'number',
                'keyword' => '',
                'format' => '',
                'field' => '',
            );
            $dataDefault = array(
                'order' => '0',
                'format' => '1',
            );
            $dataDefault["field"] = "*";
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $condition = array();
            if ($dataObj->request->keyword) {
                switch ($dataObj->request->type) {
                    case 1:
                        $raw=new Db_raw();
                        $raw->setContent("LOCATE('{$dataObj->request->keyword}',`title`)");
                        $condition[] = array(
                            $raw, ">", 0
                        );
                        break;
                }
            }
            //处理 排序  设置默认0
            $sortColumn = "id";
            $sortDirection = $dataObj->request->order % 2 === 1 ? "ASC" : "DESC";   //单数升序 双数降序 0也为降序
            switch ($dataObj->request->order) {
                case 1:
                case 2:  // id 升序
                    $sortColumn = "id";
                    break;
                case 3:
                case 4:  // 排序 升序
                    $sortColumn = "sort";
                    break;
            }
            try {
                $result = Db()->name(app("cmsTable")::single_page())->order($sortColumn, $sortDirection)->field($dataObj->request->field)->where($condition)->paginate();
                if ($result && $result["data"]) {
                    foreach ($result["data"] as $key => $val) {
                        if ($dataObj->request->format) {
                            $result["data"][$key] = $this->detailed($val, $dataObj->request->format);
                        }
                    }
                }
                $final_arr["result"] = $result;
            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    public function __call($name, $arguments)
    {
        return recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::UNDEFINED_METHOD, lang("sys.noMethodDefined"), $name, $arguments);
    }


    //获取排序权重最大值
    private function getSortWeightsMax(): int
    {
        try {
            $tbPre = app("cmsTable")::single_page();
            $sql = "SELECT MAX(sort) as MAX FROM {$tbPre}  ";
            $result = Db()->find($sql);
        } catch (\Throwable $e) {
            //内部使用,失败直接返回0
            return 0;
        }
        return $result["MAX"] ? $result["MAX"] : 0;   //第一次添加可能为 null
    }

    /**
     * 更新数据修改级别
     * @param string $paramObj
     */
    public function updateLevel($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'id' => 'require',
                "level" => "between:0,127",
            );

            $dataDefault = array();
            $dataDefault["verify"] = 1;
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        if ($final_arr["error_no"] == 0) {
            $ids = is_array($dataObj->request->id) ? $dataObj->request->id : explode(",", $dataObj->request->id);
            $condition = array();
            $condition[] = array(
                "id", "in", $ids
            );

            $data = array();
            $allowUpdates = ["level"]; //允许更新的字段
            foreach ($dataObj->request as $key => $value) {
                if (in_array($key, $allowUpdates) && $value !== null) {
                    $data[$key] = $value;
                }
            }

            if ($data) {
                try {
                    $data["updateTime"] = time();
                    $result = Db()->name(app("cmsTable")::single_page())->where($condition)->data($data)->update();
                    $return = array();
                    $return["id"] = $dataObj->request->id;
                    $return["affected_rows"] = $result["affected_rows"];
                    $final_arr["result"] = $return;
                } catch (\Throwable $e) {
                    $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
                }
            } else {
                $return = array();
                $return["id"] = $dataObj->request->id;
                $return["affected_rows"] = 0;
                $final_arr["result"] = $return;
            }
        }
        return $final_arr;
    }

    /**
     * 更新数据
     * @param string $paramObj
     */
    public function updateSortBatch($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();
        $dataObj->affected_rows = 0;

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'data' => 'require|array',
            );

            $dataDefault = array();
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        // 循环设置
        foreach ($dataObj->request->data as $tempArray) {
            $tempObj = paramsObj();
            $tempObj->request = paramsObj();
            $tempObj->data = paramsObj();
            $tempObj->data->use_trans = false;
            $tempObj->result = new \ArrayObject();
            if ($final_arr["error_no"] == 0) {
                $mixed = parseToArr($paramObj, "mixed", 0);
                $params = $tempArray;
                $messages = parseToArr($paramObj, "messages", array());
                $rules = array(
                    'id' => 'require|number',
                    'sort' => 'require|number',
                    'verify' => '',
                );

                $dataDefault = array();
                $dataDefault["verify"] = 1;
                $paramsObj = paramsObj();
                $paramsObj->params = $params;
                $paramsObj->mixed = $mixed;
                $paramsObj->rules = $rules;
                $paramsObj->messages = $messages;
                $paramsObj->dataDefault = $dataDefault;
                $checkResult = app("verifyParam")::validatorRequest($paramsObj);
                if ($checkResult["error_no"] == 0) {
                    $tempObj->request = $checkResult["result"];
                } else {
                    $final_arr = logCallErrorMsg($final_arr, $checkResult);
                }
            }
            if ($final_arr["error_no"] == 0) {
                if ($tempObj->request->verify) {
                    $paramsObj = paramsObj();
                    $paramsObj->params = array(
                        "id" => $tempObj->request->id,
                        "verify" => 1,
                    );
                    $checkResult = $this->info($paramsObj);
                    if ($checkResult["error_no"] == 0) {

                    } else {
                        $final_arr = logCallErrorMsg($final_arr, $checkResult);
                    }
                }
            }

            if ($final_arr["error_no"] == 0) {
                $ids = is_array($tempObj->request->id) ? $tempObj->request->id : array($tempObj->request->id);
                $condition = array();
                $condition[] = array(
                    "id", "in", $ids
                );

                $data = array();
                $allowUpdates = ["SortWeights"]; //允许更新的字段
                foreach ($dataObj->request as $key => $value) {
                    if (in_array($key, $allowUpdates) && $value !== null) {
                        $data[$key] = $value;
                    }
                }
                if ($data) {
                    try {
                        $result = Db()->name(app("cmsTable")::single_page())->where($condition)->data($data)->update();
                        $return = array();
                        $return["id"] = $dataObj->request->id;
                        $return["affected_rows"] = $result["affected_rows"];
                        $final_arr["result"] = $return;
                    } catch (\Throwable $e) {
                        $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
                    }
                } else {
                    $return = array();
                    $return["id"] = $tempObj->request->id;
                    $return["affected_rows"] = 0;
                    $final_arr["result"] = $return;
                }
            }

            if ($final_arr["error_no"] != 0) { //遇到失败就跳出
                break;
            }
            $dataObj->affected_rows += $final_arr["result"]["affected_rows"];//统计成功数量
        }

        return $final_arr;
    }
}